import 'package:flutter/material.dart';
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

//一种允许用户使用给定的相机拍照的屏幕
// A screen that allows users to take a picture using a given camera.
class TakePictureScreen extends StatefulWidget {
  const TakePictureScreen({
    Key? key,
    required this.camera,
  }) : super(key: key);

  final CameraDescription camera;

  @override
  TakePictureScreenState createState() => TakePictureScreenState();
}

class TakePictureScreenState extends State<TakePictureScreen> {
  late CameraController _controller;
  late Future<void> _initializeControllerFuture;

  @override
  void initState() {
    super.initState();
    //从相机显示当前输出， 创建一个CameraController 是真正的相机实例化对象, 我们可以用它来进行录制, 拍照等等
    // To display the current output from the Camera,
    // create a CameraController.
    _controller = CameraController(
      // Get a specific camera from the list of available cameras.从可用相机列表中获取一个特定的相机。
      widget.camera,
      // Define the resolution to use.定义要使用的分辨率。
      // 480p (640x480 on iOS, 720x480 on Android and Web) medium,
      ResolutionPreset.medium,
    );
    //接下来，初始化控制器。这将返回Future。
    // Next, initialize the controller. This returns a Future.
    _initializeControllerFuture = _controller.initialize();
  }

  @override
  void dispose() {
    // Dispose of the controller when the widget is disposed.
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('拍摄正面照'),
        backgroundColor: Colors.black,
      ),
      //控件的初始化之前，必须等待控制器初始化,相机预览。使用FutureBuilder显示加载微调轮，直到控制器已初始化。
      // You must wait until the controller is initialized before displaying the
      // camera preview. Use a FutureBuilder to display a loading spinner until the
      // controller has finished initializing.
      body: FutureBuilder<void>(
        future: _initializeControllerFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            // If the Future is complete, display the preview.如果Future已完成，则显示预览，拍照窗口出现
            /*return Column(
              children: <Widget>[
                Expanded(
                  child: Container(
                    child: Padding(
                      padding: const EdgeInsets.all(0.0),
                      child: Center(
                        child: CameraPreview(_controller),
                      ),
                    ),
                    decoration: BoxDecoration(
                      color: Colors.black,
                      border: Border.all(
                        color:Colors.grey,
                        width: 3.0,
                      ),
                    ),
                  ),
                ),
                //按钮开始

              ],
            );*/
            return Stack(
                children: <Widget>[
                    CameraPreview(_controller),
                  // CameraPreview(_controller),
                  //左上角返回按钮
                  Positioned(
                    top: 15,
                    left: 10,
                    child: IconButton(
                      icon: Icon(
                        Icons.chevron_left,
                        color: Colors.white,
                        size: 30,
                      ),
                      onPressed: () {
                        Navigator.pop(context);
                      },
                    ),
                  ),
                  //左下角提示按钮
                  Positioned(
                    bottom: 20,
                    left: 30,
                    child: IconButton(
                      icon: Icon(
                        Icons.announcement_outlined,
                        color: Colors.white,
                        size: 30,
                      ),
                      onPressed: () {

                      },
                    ),
                  ),
                  //右下角选择图片
                  Positioned(
                    right: 30,
                    bottom: 20,
                    child: IconButton(
                        icon: Icon(Icons.picture_in_picture),
                        onPressed: () async {
                          final pickedImage =await ImagePicker().pickImage(source: ImageSource.gallery);
                          await Navigator.of(context).push(
                            MaterialPageRoute(
                              builder: (context) => DisplayPictureScreen(
                                //将自动生成的路径传递到显示图片窗口小部件。
                                // Pass the automatically generated path to the DisplayPictureScreen widget.
                                imagePath: pickedImage!.path,
                              ),
                            ),
                          );
                        }
                    ),
                  )
                ]);
          } else {
            // Otherwise, display a loading indicator. 否则，显示加载中动态样式
            return const Center(child: CircularProgressIndicator());
          }
        },
      ),
      //拍照按钮
      floatingActionButton: FloatingActionButton(
        child: const Icon(
            Icons.camera_alt_outlined
        ),
        backgroundColor: Colors.blue,
        // Provide an onPressed callback.
        onPressed: () async {
          // Take the Picture in a try / catch block. If anything goes wrong,catch the error.
          try {
            // Ensure that the camera is initialized.确保摄像机已初始化。
            await _initializeControllerFuture;

            // Attempt to take a picture and get the file `image` where it was saved.
            // 尝试拍摄一张照片，并获得文件' image '在那里它被保存
            final image = await _controller.takePicture();

            //照片拍摄完成，路由到显示页面
            // If the picture was taken, display it on a new screen.
            await Navigator.of(context).push(
              MaterialPageRoute(
                builder: (context) => DisplayPictureScreen(
                  //将自动生成的路径传递到显示图片窗口小部件。
                  // Pass the automatically generated path to the DisplayPictureScreen widget.
                  imagePath: image.path,
                ),
              ),
            );
          } catch (e) {
            // If an error occurs, log the error to the console. 如果发生错误，将错误记录到控制台。
            print(e);
          }
        },
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,//居中浮动

    );
  }
}

// A widget that displays the picture taken by the user.显示用户所拍照片的小部件。
class DisplayPictureScreen extends StatelessWidget {
  final String imagePath;

  const DisplayPictureScreen({Key? key, required this.imagePath})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: AppBar(title: const Text('Display the Picture')),
      // The image is stored as a file on the device. Use the `Image.file`
      body: Container(
        color: Colors.black,
        height: double.infinity,
        child:Stack(
          children: [
            Align(
              alignment: Alignment.center,
              child: Image.file(
                File(imagePath),
                alignment: Alignment.center,
              ),
            ),
            Positioned(
              left: 22.0,
              bottom: 9.0,
              child: IconButton(
                icon:Icon(Icons.clear, size: 40, color: Colors.white),
                onPressed: (){

                },
              ),
            ),
            Positioned(
              right: 22.0,
              bottom: 9.0,
              child: IconButton(
                icon:Icon(Icons.check, size: 40, color: Colors.white),
                onPressed: (){

                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
